package neusoft.yuejian_11;

import android.content.SharedPreferences;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.os.Bundle;

import neusoft.yuejian_11.base.BaseActivity;
import neusoft.yuejian_11.fragment.LoginFragment;
import neusoft.yuejian_11.fragment.MainFragment;
import neusoft.yuejian_11.fragment.WelcomeFragment;


public class MainActivity extends BaseActivity {
    private FragmentManager fragmentManager;
    private FragmentTransaction transaction;
    private SharedPreferences Preferences;
    private final String fileName="yuejian";
    private final  int mode=MODE_PRIVATE;//权限
    private LoginFragment loginFragment;
    private WelcomeFragment welcomeFragment;
    private MainFragment mainFragment;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Preferences=getSharedPreferences(fileName,mode);
        fragmentManager=getSupportFragmentManager();
        boolean loginState=getLoginState();
        if(loginState){
            showMainFragment();

           u_id= Integer.parseInt(getSavedUserId());//获取已经存储的用户ID
        }else{
            showWelcomeFragment();
        }
    }
    public void showLoginFragment(){
        transaction=fragmentManager.beginTransaction();
        loginFragment=new LoginFragment();
        transaction.add(R.id.fragment_holder,loginFragment);
        transaction.commit();
    }

    public void showWelcomeFragment(){
        transaction=fragmentManager.beginTransaction();
        welcomeFragment=new WelcomeFragment();
        transaction.add(R.id.fragment_holder,welcomeFragment);
        transaction.commit();
    }
    public void showMainFragment(){
        transaction=fragmentManager.beginTransaction();
        mainFragment=new MainFragment();
        transaction.add(R.id.fragment_holder,mainFragment);
        transaction.commit();
    }
    public void replaceLoginFragment(){
        mainFragment=new MainFragment();
        transaction=fragmentManager.beginTransaction();
        transaction.replace(R.id.fragment_holder,mainFragment);
        transaction.commit();
    }
    private boolean getLoginState(){
        String u_id=getSavedUserId();
        return !u_id.equals("-1");
    }
    //保存登录（读出）
    private String getSavedUserId(){
        String u_id=Preferences.getString("u_id","-1");//读到-1没有登录过
        return u_id;
    }
    //写登录
    public void setSavedUserId(int u_id){
        SharedPreferences.Editor editor=Preferences.edit();
        editor.putString("u_id",String.valueOf(u_id));
        editor.commit();
    }
}

